#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2022/6/3 1:30
# @Author  : Samge
import random

import requests

from itkz.resources.utils import file_util
from itkz.spider_ext.datas import data_agent

TEST_URL: str = 'https://www.itkz.net/api/goods?current=1&categoryId=&labelId=&keyword='


def get_proxy_list(data: dict) -> dict:
    txt: str = file_util.read_txt_file('proxy_dict.txt')
    if txt:
        return eval(txt)
    temp_dict: dict = {}
    for key, value in data.items():
        try:
            proxies = {"http": key, "https": key}
            user_agent = random.choice(data_agent.user_agent_list)
            headers = {'User-Agent': user_agent}
            r = requests.get(TEST_URL, proxies=proxies, headers=headers, timeout=1)
            if r.status_code == 200:
                temp_dict[key] = '1'
            else:
                print(f'无效代理：（{key}），跳过')
        except Exception as e:
            print(f'无效代理：（{key}），跳过 {e}')
    file_util.save_txt_file(str(temp_dict), 'proxy_dict.txt')
    return temp_dict
